package com.example.oneSpringMVC.interceptor;


import com.alibaba.fastjson.JSON;
import com.example.oneSpringMVC.common.Result;
import com.example.oneSpringMVC.utils.RedisUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * @description: 拦截Interceptor的HttpServletRequest请求头
 * @author: xinTong
 * @create: 2024-01-26 14:18
 **/
@Component
public class Interceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 响应数据格式
        response.setContentType("application/json;charset=utf-8");
        // 1、获取对象head userId
        String userId = request.getHeader("userId");
        // 2、去redis查询是否存在userId
        String obj = redisUtils.get("rbac:login_employee:" + userId);
        // 3、为空，进行拦截，没有登录
        if (StringUtils.isEmpty(obj)){
            Result result = new Result(401,"操作失败","fail",null);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        // 4、不为空，放行
        return true;
    }

}
